﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using SevenZip;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.DataAccess;
using CommonModule;

namespace Web.Views.DataManage.PLuploads
{
    /// <summary>
    /// FileUploadHandler 的摘要说明
    /// </summary>
    public class FileUploadHandler : IHttpHandler
    {

        public void ProcessRequestWeb(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";
                string fileName = context.Request.QueryString["fileName"];
                string fileExtentionName = Path.GetExtension(fileName);
                string tempPath = System.IO.Path.Combine(context.Request.PhysicalApplicationPath + "\\Views\\DataManage\\PLuploads\\tempDatas", fileName);
                long fileSize = long.Parse(context.Request.QueryString["fileSize"]);
                int sendCount = int.Parse(context.Request.QueryString["sendCount"]);
                string pid = context.Request.QueryString["pid"];
                string fileType = context.Request.QueryString["fileType"];

                FileMode fileMode;
                if (sendCount == 1)
                {
                    fileMode = FileMode.Create;
                }
                else
                {
                    fileMode = FileMode.Append;
                }
                using (FileStream fileStream = new FileStream(tempPath, fileMode))
                {
                    int tempInt = 0;
                    while ((tempInt = context.Request.InputStream.ReadByte()) > 0)
                    {
                        fileStream.WriteByte((byte)tempInt);
                    }
                    fileStream.Flush();
                    if (fileStream.Length == fileSize)
                    {
                        fileStream.Close();
                        if (fileExtentionName.ToLower() == ".rar" || fileExtentionName.ToLower() == ".zip" || fileExtentionName.ToLower() == ".7z")
                        {
                            SevenZipExtractor sze = new SevenZipExtractor(tempPath);
                            int archiveFileCount = sze.ArchiveFileData.Count;
                            if (archiveFileCount > 0)
                            {
                                string extractPath = Path.GetDirectoryName(tempPath) + "\\" + Path.GetFileName(tempPath);
                                Directory.CreateDirectory(extractPath);
                                for (int i = 0; i < sze.ArchiveFileData.Count; i++)
                                {
                                    if (!sze.ArchiveFileData[i].IsDirectory)
                                    {
                                        sze.ExtractFiles(extractPath, i);
                                    }
                                }
                            }
                        }
                        if (fileType == "1")
                        {

                        }
                        else if (fileType == "2")
                        {

                        }
                    }
                    context.Response.Write("OK");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                try
                {
                    string objectId = context.Request.QueryString["EntityId"];
                    string userId = context.Request.QueryString["UserId"];
                    string type = context.Request.QueryString["Type"];
                    string catalogId = context.Request.QueryString["CatalogId"];
                    string flag = context.Request.QueryString["Flag"];
                    if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(objectId) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(catalogId))
                    {
                        throw new Exception("用户名或著录项ID或分类为空！");
                    }
                    HttpPostedFile file = context.Request.Files[0];
                    string fileName = file.FileName;
                    string fileExtension = Path.GetExtension(fileName);
                    if (fileExtension.StartsWith("."))
                    {
                        fileExtension = fileExtension.Remove(0, 1);
                    }
                    fileName = fileName.Replace("'", "''");

                    DataHelper dataHelper = new DataHelper();
                    string attachmentId = string.Concat(Guid.NewGuid());
                    switch (type)
                    {
                        case "SingleWell":
                            dataHelper.UploadAttachment("SingleWell", attachmentId, "singlewell", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                            break;
                        case "Archive":
                            if (flag == "PageFile")
                            {
                                dataHelper.UploadAttachment("PageFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                break;
                            }
                            else
                            {
                                switch (catalogId)
                                {
                                    case "1": //文书类 W
                                        dataHelper.UploadAttachment("DocumentFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "2": //光盘类 E
                                        dataHelper.UploadAttachment("CDKind", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "3": //科学技术研究类 F
                                        dataHelper.UploadAttachment("Technology", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "4": //建设项目类 G
                                        dataHelper.UploadAttachment("BuildProjectFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "5": //设备仪器类 H
                                        dataHelper.UploadAttachment("Equipment", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "61": //会计凭证 I01
                                    case "62": //会计账簿 I02
                                    case "63": //财务报告 I03
                                    case "64": //其他 I04
                                        dataHelper.UploadAttachment("AccountFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "71": //勘探综合
                                    case "72": //勘探单井
                                        dataHelper.UploadAttachment("oilsearch", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "81": //声像
                                    case "82": //声像
                                    case "83": //声像
                                        dataHelper.UploadAttachment("audiofile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "91": //荣誉 R01
                                        dataHelper.UploadAttachment("RealKind", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "101":
                                        dataHelper.UploadAttachment("DocumentFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "102":
                                        dataHelper.UploadAttachment("DocumentFile", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "7101":
                                        dataHelper.UploadAttachment("oilsearch", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    case "7102":
                                        dataHelper.UploadAttachment("oilsearch", attachmentId, "archive", objectId, fileName, Convert.ToInt32(file.InputStream.Length / 1024.0), fileExtension, file.InputStream, "", "", userId, "");
                                        break;
                                    default:
                                        throw new Exception("CatalogId为空或不存在");
                                }
                            }
                            break;
                        default:
                            throw new Exception("Type为空或不存在");
                    }
                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
            }
            else
            {
                context.Response.Write("文件上传失败！");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}